<template>
  <div class="app-container">
    <el-form ref="form" :model="form" inline>
      <el-form-item label="合同名称" prop="contractName">
        <el-input v-model="form.contractName" clearable></el-input>
      </el-form-item>
      <el-form-item label="合同id" prop="contractId">
        <el-input v-model="form.contractId" clearable></el-input>
      </el-form-item>
      <el-form-item label="合同状态" prop="contractStatus">
        <el-select v-model="form.contractStatus" clearable placeholder="请选择合同状态">
          <el-option v-for="item in statusData" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset('form')">重置</el-button>
      </el-form-item>
      <el-button icon="el-icon-download" @click="clickBatchDownLoad" style="float: right;">批量下载</el-button>
    </el-form>
    <el-table
      v-loading="listLoading"
      :data="contractList"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
      >
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column label="合同名称">
        <template slot-scope="scope">
          <el-button type="text" @click="onShowDetail(scope.row)">{{ scope.row.FlowName }}</el-button>
        </template>
      </el-table-column>
      <el-table-column label="用工单位" v-if="type===1">
          <template slot-scope="scope">
            {{ scope.row.tenantName }}
          </template>
        </el-table-column>
        <el-table-column label="用工单位经办人" v-if="type===1">
          <template slot-scope="scope">
            {{ scope.row.tenantAgentName }}
          </template>
        </el-table-column>
        <el-table-column label="用工单位经办人联系方式" v-if="type===1">
          <template slot-scope="scope">
            {{ scope.row.tenantAgentMobile }}
          </template>
        </el-table-column>
      <el-table-column label="工人姓名" v-if="type===2">
        <template slot-scope="scope">
          {{ scope.row.workerName }}
        </template>
      </el-table-column>
      <el-table-column label="工人联系方式" width="160" v-if="type===2">
        <template slot-scope="scope">
          {{ scope.row.workerMobile }}
        </template>
      </el-table-column>
      <el-table-column label="合同签署截止时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.DeadLine | dateFilter }}
        </template>
      </el-table-column>
      <el-table-column label="合同开始时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.contractStartTime | dateFilter }}
        </template>
      </el-table-column>
      <el-table-column label="合同结束时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.contractEndTime | dateFilter }}
        </template>
      </el-table-column>
      <el-table-column label="状态" width="120">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.FlowStatus" size="small" :type="handleStatusColor(scope.row.FlowStatus)">{{ scope.row.FlowStatus.trim() | flowStatusFilter }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="downloadContract(scope.row)"
            >下载</el-button>
          <el-button
            v-if="['INIT', 'PART'].includes(scope.row.FlowStatus)"
            type="text"
            size="small"
            @click="remindToSign(scope.row)"
            >提醒签署</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <div class="contract-page">
      <el-pagination
        small
        layout="prev, pager, next, total, sizes, jumper"
        :page-size="pageSize"
        :page-sizes="[5, 10, 20, 50]"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
      >
      </el-pagination>
    </div>
  </div>
</template>

<script>
import { getContractList, createSignUrl, contractDownload } from '@common/api/contract';
import { FLOW_STATUS_TEXT } from '@common/consts/status';

import moment from 'moment';

export default {
  name: 'contractTable',
  props: {
    type: {
      type: Number,
    },
    filter: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      contractList: [],
      listLoading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      form: {
        contractName: '',
        contractId: '',
        contractStatus: '',
      },
      selectedData: [],
    };
  },
  computed: {
    statusData() {
      const temp = [];
      // eslint-disable-next-line no-restricted-syntax
      for (const k in FLOW_STATUS_TEXT) {
        temp.push({
          label: FLOW_STATUS_TEXT[k],
          value: k,
        });
      }
      return temp;
    },
  },
  filters: {
    dateFilter(time) {
      if (time.length > 10) {
        return time ? moment(time).format('YYYY-MM-DD HH:mm:ss') : '';
      }
      return time ? moment(time * 1000).format('YYYY-MM-DD HH:mm:ss') : '';
    },
    // dateFilter2(time) {
    // return time ? time.replace(/年/, '-').replace(/月/, '-')
    //   .replace(/日/, '') : '';
    // },
    flowStatusFilter(status) {
      return status ? FLOW_STATUS_TEXT[status] : '';
    },
  },
  created() {
    if (this.filter?.contractName) {
      this.form.contractName = this.filter.contractName;
    }
    this.fetchContractList();
  },
  methods: {
    handleSizeChange(val) {
      this.pageSize = val;
      this.fetchContractList();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchContractList();
    },

    // 获取合同列表
    async fetchContractList() {
      this.listLoading = true;
      const res = await getContractList({
        limit: this.pageSize,
        offset: (this.currentPage - 1) * this.pageSize,
        contractType: this.type, //  1:劳动派遣合同  2:劳动合同
        contractName: this.form.contractName,
        contractId: this.form.contractId,
        contractStatus: this.form.contractStatus,
      });
      if (res?.data?.contracts?.length) {
        this.contractList = res?.data?.contracts;
      } else {
        this.contractList = [];
      }
      this.total = res?.data?.totalCount || 0;
      this.listLoading = false;
    },
    // 查看详情
    onShowDetail(row) {
      this.$router.push(`/contract/detail/${row.FlowId}`);
    },
    // 提醒签署
    async remindToSign(row) {
      // updateContract(row).then(async () => {
      const res = await createSignUrl(row);
      if (res?.data?.SignUrlInfos?.length) {
        const nodeElement = (
            <div>
              请复制链接 <el-link type='primary'>{res?.data?.SignUrlInfos[0].SignUrl}</el-link> 使用手机浏览器打开
            </div>
        );
        this.$alert(nodeElement, '提示', {
          confirmButtonText: '确定',
        });
      }
      // });
    },

    // 搜索
    onSearch() {
      this.fetchContractList();
    },
    // 重置
    onReset(formName) {
      this.$refs[formName].resetFields();
      this.fetchContractList();
    },

    handleSelectionChange(val) {
      this.selectedData = val;
    },

    // 批量下载
    clickBatchDownLoad() {
      if (this.selectedData.length === 0) {
        return this.$message.warning('请选择先选择需要下载项');
      }
      this.downloadContract(this.selectedData);
    },

    // 下载
    async downloadContract(data) {
      let flowIds = [];
      if (Array.isArray(data)) {
        flowIds = data.map(i => i.FlowId);
      } else if (data?.FlowId) {
        flowIds.push(data?.FlowId);
      }
      if (flowIds.length) {
        const res = await contractDownload({ flowIds });
        if (res?.code === 20000 && res?.data?.FlowResourceUrlInfos?.length) {
          const utlList = res.data.FlowResourceUrlInfos;
          for (let i = 0; i < utlList.length; i++) {
            const hiddenIFrameID = `hiddenDownloader${utlList[i].FlowId}`;
            const iframe = document.createElement('iframe');
            iframe.id = hiddenIFrameID;
            iframe.style.display = 'none';
            document.body.appendChild(iframe);
            iframe.src = utlList[i].ResourceUrlInfos ?.[0]?.Url;// 直接下载，不会弹出新的页面
          }
        } else {
          return this.$message.error('合同下载失败');
        }
      }
    },

    // 状态处理
    handleStatusColor(status) {
      if (['INIT', 'PART', 'WILLEXPIRE'].includes(status.trim())) {
        return '';
      }
      if (status.trim() === 'ALL') {
        return 'success';
      }
      if (['CANCEL', 'REJECT', 'DEADLINE', 'EXCEPTION', 'STOPPED'].includes(status.trim())) {
        return 'danger';
      }
      return '';
    },

  },
};
</script>

<style lang="scss">
.contract-page {
  padding: 20px 0;
  text-align: right;
}
</style>

